export default class extends think.Service {
  async info(id: number) {
    const $model = think.model("member");
    const $pk = $model.pk;
    const info = await $model.where({ [$pk]: id }).find();
    return info;
  }

  async wechat(userinfo: any) {
    const { unionid, openid, login_ip } = userinfo;
    let wechat_where: any = {
      is_delete: ["=", 0],
    };
    const $WechatModel = think.model("member_wechat");
    const $MemberModel = think.model("member");
    const $MemberPk = $MemberModel.pk;
    const $MemberWechatPk = $WechatModel.pk;
    if (unionid) {
      wechat_where["unionid"] = unionid;
    } else {
      wechat_where["openid"] = openid;
    }
    const member_wechat = await $WechatModel.where(wechat_where).find();

    if (think.isEmpty(member_wechat)) {
      const result = await $MemberModel.transaction(async () => {
        userinfo.create_time = think.formatter();

        const insertId = await $MemberModel.add(userinfo);

        const $MemberWechatModel = $WechatModel.db($MemberModel.db());
        let member_wechat_id = await $MemberWechatModel.add({
          member_id: insertId,
          ...userinfo,
        });
        const results = await $MemberModel
          .where({ [$MemberPk]: insertId })
          .update({
            member_wechat_id: member_wechat_id,
          });
        const user = {
          [$MemberPk]: insertId,
          ...userinfo,
        };
        return user;
      });

      return result;
    } else {
      const userInfo = await $MemberModel
        .where({ [$MemberPk]: member_wechat.member_id })
        .find();
      return userInfo;
    }
  }
}
